import { Component, Injector } from '@angular/core';
import { AppComponentBase } from '@abp/components';
import {
  UserServiceProxy,
  UserListDto,
  SwitchEntityInputDtoOfInt64,
} from '@abp/service-proxies/service-proxies';
import { CreateOrEditUserComponent } from './create-or-edit-user/create-or-edit-user.component';
import { EditUserPermissionsComponent } from './edit-user-permissions/edit-user-permissions.component';

@Component({
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.less'],
})
export class UsersComponent extends AppComponentBase {
  selectedPermission = '';

  /** 排序 */
  sortValue = null;
  sortKey = null;

  /** 加载 */
  skeletonLoading = true;
  switchloading = false;

  /** 模糊搜索的文本 */
  filterText = '';

  /**
   * 选中的角色Ids过滤
   */
  role: number;

  constructor(injector: Injector, private userService: UserServiceProxy) {
    super(injector);
  }

  ngOnInit(): void {
    this.searchData();
  }

  /**
   * 刷新表格数据
   * @param args
   */
  refresh(): void {
    this.searchData();
  }

  sort(sort: { key: string; value: string }): void {
    this.tableHelper.sort = sort;
    this.searchData();
  }

  searchData(reset: boolean = false): void {
    if (reset) {
      this.tableHelper.pageIndex = 1;
    }
    this.tableHelper.isLoading = true;

    this.userService
      .getUsers(
        this.filterText,
        undefined,
        this.role,
        false,
        this.tableHelper.getSorting(),
        this.tableHelper.getMaxResultCount(),
        this.tableHelper.getSkipCount(),
      )
      .subscribe(data => {
        this.tableHelper.isLoading = false;
        this.tableHelper.totalRecordsCount = data.totalCount;
        this.tableHelper.records = data.items;
      });
  }

  /**
   * 根据角色列表进行数据展示
   * @param roles 角色列表信息
   */
  getRolesAsString(roles): string {
    let roleNames = '';
    for (let j = 0; j < roles.length; j++) {
      if (roleNames.length) {
        roleNames = roleNames + ', ';
      }
      roleNames = roleNames + roles[j].roleName;
    }
    return roleNames;
  }

  createBuildingPlan(): void {
    let config = this.drawerConfig(
      '添加用户',
      CreateOrEditUserComponent,
      {
        id: undefined,
      },
      500,
    );
    const drawerRef = this.drawerService.create(config);
    drawerRef.afterOpen.subscribe(() => {});
    drawerRef.afterClose.subscribe(data => {
      if (data) {
        this.searchData();
      }
    });
  }

  editBuildingPlan(data: UserListDto): void {
    let config = this.drawerConfig(
      '修改用户:' + data.userName,
      CreateOrEditUserComponent,
      {
        id: data.id,
      },
      500,
    );
    const drawerRef = this.drawerService.create(config);
    drawerRef.afterOpen.subscribe(() => {});
    drawerRef.afterClose.subscribe(data => {
      if (data) {
        this.searchData();
      }
    });
  }

  editPermissionsBuildingPlan(data: UserListDto): void {
    let config = this.drawerConfig(
      '权限:' + data.userName,
      EditUserPermissionsComponent,
      {
        id: data.id,
      },
      500,
    );
    const drawerRef = this.drawerService.create(config);
    drawerRef.afterOpen.subscribe(() => {});
    drawerRef.afterClose.subscribe(data => {
      if (data) {
        this.searchData();
      }
    });
  }

  deleteConfirm(id: number): void {
    this.userService.deleteUser(id).subscribe(() => {
      this.searchData();
      this.notify.success('删除成功！');
    });
  }

  clickIsEmailConfirmedSwitch(data: UserListDto): void {
    const input = new SwitchEntityInputDtoOfInt64();
    input.id = data.id;
    input.switchValue = !data.isEmailConfirmed;
    data.isEmailConfirmed = !data.isEmailConfirmed;
    this.userService
      .updateIsEmailConfirmedSwitchAsync(input)
      .subscribe(result => {
        if (data.isEmailConfirmed) {
          this.notify.success('验证通过!');
        } else {
          this.notify.success('验证不通过!');
        }
      });
  }

  clickIsActiveSwitch(data: UserListDto) {
    const input = new SwitchEntityInputDtoOfInt64();
    input.id = data.id;
    input.switchValue = !data.isActive;
    data.isActive = !data.isActive;
    this.userService.updateIsActiveSwitchAsync(input).subscribe(result => {
      if (data.isActive) {
        this.notify.success('激活成功!');
      } else {
        this.notify.success('锁定成功!');
      }
    });
  }
}
